package com.cheer.ba.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.footview.CustomerFooter;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.listener.OnItemClickListener;
import com.cheer.ba.model.OilCardInfoModel;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.adapter.DriverListAdp;
import com.cheer.ba.view.adapter.FrequentlyAreaAdp;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.widget.headview.CheerHeadView;
import com.cheer.lib_recycle_swipe.Closeable;
import com.cheer.lib_recycle_swipe.OnSwipeMenuItemClickListener;
import com.cheer.lib_recycle_swipe.SwipeMenu;
import com.cheer.lib_recycle_swipe.SwipeMenuCreator;
import com.cheer.lib_recycle_swipe.SwipeMenuItem;
import com.cheer.lib_recycle_swipe.SwipeMenuRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 司机列表
 */
public class DriversListAty extends BaseCommAty {

    @BindView(R.id.id_drivers_xrefreshv)
    XRefreshView mXRefreshView;
    @BindView(R.id.id_drivers_recyclev)
    SwipeMenuRecyclerView mRecycleView;
    private DriverListAdp mDriverListAdp;
    List<OilCardInfoModel> mDriverLists = new ArrayList<OilCardInfoModel>();
    //柴油卡号
    private String mCardNum;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_driver_list, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return !mDriverLists.isEmpty();
    }

    @Override
    public void initView() {
        mCardNum = getIntent().getStringExtra(IntentKey.General.KEY_DATA);
        if (StringUtils.isEmpty(mCardNum)) {
            setTitleText("我的车辆");
        } else {
            setTitleText("司机列表");
        }
        setXRefreshView(mXRefreshView, true, true, false, false, new CheerHeadView(aty), new CustomerFooter(aty));
        mRecycleView.setLayoutManager(new LinearLayoutManager(aty));
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setItemAnimator(new DefaultItemAnimator());
        // 为SwipeRecyclerView的Item创建菜单就两句话，不错就是这么简单：
        // 设置菜单创建器。
        mRecycleView.setSwipeMenuCreator(swipeMenuCreator);
        // 设置菜单Item点击监听。
        mRecycleView.setSwipeMenuItemClickListener(menuItemClickListener);
        mRecycleView.smoothOpenRightMenu(0);
        mRecycleView.setNestedScrollingEnabled(false);

        mDriverListAdp = new DriverListAdp(mDriverLists);
        mDriverListAdp.setOnItemClickListener(onItemClickListener);
        mRecycleView.setAdapter(mDriverListAdp);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initData() {
        setTitleRight("去添加", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加司机
                showActivity(aty, AddDriversAty.class);
            }
        });
        loadData(true, false);
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData(false, false);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                loadData(false, true);
            }
        });
    }

    /**
     * 加载数据
     */
    public void loadData(boolean isShLowoad, boolean loadMore) {
        ((OilMealPresenter) presenter).getDriverList(isShLowoad, loadMore, "", "", "", "", "");
        if (!isShLowoad) {
            if (loadMore) {
                if (hasDataInPage()) {
                    stopLoadComplete(mXRefreshView, 2000);
                } else {
                    stopLoadMore(mXRefreshView, 2000);
                }
            } else {
                stopRefresh(mXRefreshView, 2000);
            }
        }
    }

    @OnClick(R.id.id_search_top)
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_search_top:
                Intent intent = new Intent(aty, SearchDriversAty.class);
                intent.putExtra(IntentKey.General.KEY_DATA, mCardNum);
                showActivity(aty, intent);
                break;
        }
    }

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int size = getResources().getDimensionPixelSize(R.dimen.item_height2);
            if (viewType == FrequentlyAreaAdp.VIEW_TYPE_NONE) {
                //不添加滑动
            } else {
                SwipeMenuItem addItem = new SwipeMenuItem(aty)
                        .setBackgroundDrawable(getResources().getDrawable(R.color.color_ff3b32))
//                .setImage(R.drawable.ic_home_msg)
                        .setText("删除")
                        .setTextColor(Color.WHITE)
                        .setTextSize(16)
                        .setHeight(size)
                        .setWidth(size);
                swipeRightMenu.addMenuItem(addItem);
            }
        }
    };

    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView#RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            // 关闭被点击的菜单。
            closeable.smoothCloseMenu();
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                OilCardInfoModel model = mDriverListAdp.getItem(adapterPosition);
                //右侧菜单
                if (menuPosition == 0) {
                    //删除
                    ((OilMealPresenter) presenter).delDriverInfo(model.getUid());
                }
            }
        }
    };

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position) {
            OilCardInfoModel model = mDriverListAdp.getItem(position);
            if (null != model) {
                if (StringUtils.isEmpty(model.getCardNum())) {
                    //去关联
                    if (!StringUtils.isEmpty(mCardNum)) {
                        ((OilMealPresenter) presenter).bindDriverInfo(model.getUid(), mCardNum);
                    } else {
                        Intent card = new Intent(aty, OilCardAty.class);
                        card.putExtra(IntentKey.General.KEY_PAGE, true);
                        showActivity(aty, card);
                    }
                } else {
                    //查看流水
                    Intent intent = new Intent(aty, LookMyBillAty.class);
                    intent.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.JUMP_DEVICE);
                    intent.putExtra(IntentKey.General.KEY_ID, model.getUid());
                    showActivity(aty, intent);
                }
            }
        }
    };


    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.BIND_DRIVERS)) {
                //绑定司机成功
                if (StringUtils.isEmpty(mCardNum)) {
                    mXRefreshView.startRefresh();
                } else {
                    OilCardInfoModel model = (OilCardInfoModel) t;
                    if (null != model) {
                        SVProgressHUD.showSuccessWithStatus(aty, "绑定成功");
                        BaseEvent event = new BaseEvent();
                        event.type = ConstantTag.BIND_DRIVERS;
                        event.model = model;
                        EventBus.getDefault().post(event);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 2000);
                    }
                }
            } else if (TextUtils.equals(tag, ConstantTag.DEL_DRIVERS)) {
                //移除成功
                mXRefreshView.startRefresh();
                OilCardInfoModel model = (OilCardInfoModel) t;
                BaseEvent event = new BaseEvent();
                event.type = ConstantTag.DEL_DRIVERS;
                event.model = model;
                EventBus.getDefault().post(event);
            }
        }
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, boolean loadMore, String tag) {
        if (loadMore) {
            if (hasDataInPage()) {
                mXRefreshView.setLoadComplete(true);
            } else {
                mXRefreshView.stopLoadMore();
            }
        } else {
            mXRefreshView.stopRefresh();
        }
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.GET_DRIVERS_LIST)) {
                //获得司机列表
                List<OilCardInfoModel> mDrivers = (List<OilCardInfoModel>) t;
                if (!loadMore) {
                    mDriverLists.clear();
                }
                if (mDrivers.isEmpty()) {
                    if (loadMore) {
                        ToastUtil.showToast(getString(R.string.no_more_data));
                    } else {
                        dataStatus(3);
                    }
                } else {
                    mDriverLists.addAll(mDrivers);
                    mDriverListAdp.notifyDataSetChanged();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, ConstantTag.ADD_DRIVERS)) {
            //添加司机成功
            mXRefreshView.startRefresh();
        } else if (TextUtils.equals(type, ConstantTag.DEL_DRIVERS)) {
            //移除司机
            mXRefreshView.startRefresh();
            OilCardInfoModel model = (OilCardInfoModel) event.model;
            BaseEvent event1 = new BaseEvent();
            event1.type = ConstantTag.DEL_DRIVERS;
            event1.model = model;
            EventBus.getDefault().post(event1);
        } else if (TextUtils.equals(type, IntentKey.Oil.KEY_OIL_MODEL)) {
            OilCardInfoModel model = (OilCardInfoModel) event.model;
            if (null != model) {
                ((OilMealPresenter) presenter).bindDriverInfo(model.getUid(), model.getCardNum());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
